<?php
require_once("taskView.php");
require_once(CORE_DIR.'taskModel.php');
require_once(CORE_DIR.'userModel.php');

class getuserstaskscountAction extends authAction{

	function __construct(){
		$this->view = new taskView();
	}

	public function run($get, $post, $viewtype) {
		parent::run($get,$post,$viewtype);
		
		$tModel = new taskModel();		
		$uModel = new userModel();		
		
		$period = isset($get["period"]) ? $get["period"] : "today";
		$prjId = isset($get["prjid"]) ? $get["prjid"] : 0;
		
		$users = $uModel->getAllUsers();
		foreach ($users as $id => $user)
		{
			$users[$id]["active_tasks"] = "0";
			$users[$id]["done_tasks"] = "0";
		}
		
		$usersDoneTasks = $tModel->getUsersTasksCount($prjId, $period, 1);
		$usersActiveTasks = $tModel->getUsersTasksCount($prjId, "all", 0);
		
		foreach ($usersDoneTasks as $id => $user)
		{
			if (isset($users[$id]))
			{
				$users[$id]["id"] = $id;
				$users[$id]["nickname"] = $user["nickname"];
				$users[$id]["active_tasks"] = "0";
				$users[$id]["done_tasks"] = $user["tasks_count"];
			}
		}
		foreach ($usersActiveTasks as $id => $user)
		{
			if (isset($users[$id]))
			{
				$users[$id]["id"] = $id;
				$users[$id]["nickname"] = $user["nickname"];
				$users[$id]["active_tasks"] = $user["tasks_count"];
				if (!isset($users[$id]["done_tasks"])) $users[$id]["done_tasks"] = "0";
			}
		}
		
		$users = $this->multisort($users, "done_tasks", "id", "nickname", "active_tasks", "done_tasks");
		
		$this->view->setProperty("users", $users);
		$this->view->showUsersTasksCount();
	}
	
	function multisort($array, $sort_by, $key1, $key2=NULL, $key3=NULL, $key4=NULL){
    foreach ($array as $pos =>  $val)
        $tmp_array[$pos] = $val[$sort_by];
    arsort($tmp_array);

    foreach ($tmp_array as $pos =>  $val){
        $return_array[$pos][$sort_by] = $array[$pos][$sort_by];
        $return_array[$pos][$key1] = $array[$pos][$key1];
        if (isset($key2)){
            $return_array[$pos][$key2] = $array[$pos][$key2];
            }
        if (isset($key3)){
            $return_array[$pos][$key3] = $array[$pos][$key3];
            }
        if (isset($key4)){
            $return_array[$pos][$key4] = $array[$pos][$key4];
            }
        }
	    return $return_array;
    }	
}
?>